31

Build Your Own Game—Tic Tac Toe

31

This is what an algorithm is—​a clever, repeatable, and predictable way to perform a

task in a program.

The magic square above now looks something like this:

935

2

3

5

30

7

11

13

1001

17

19

23

7429

238

627

1495

506

FIGURE 2.28  Magic square.

Notice that each product is unique and can be easily identified as a winning number.

Here is the code to create the product for each row, which we call a “score”. If a

cell is not filled in, we assume that its value is 1, so that multiplying it has a neutral

effect (any number multiplied by 1 is the number itself). Or, as in the code below, just

do not multiply the value of that cell at all.

Function NextEmptyFormCell(ByRef, XScore)

Dim Factor(3)

Factor(1) = Array(0, 2, 3, 5)

Factor(2) = Array(0, 7, 11, 13)

Factor(3) = Array(0, 17, 19, 23)

XScore = 1

For i = 1 To 3

For j = 1 To 3

If UserForm1.Controls("TextBox" & (i - 1) * 3 + j) = "X" Then

XScore = XScore * Factor(i)(j)

End If

Next j

Next i

End Function

FIGURE 2.29  Next Empty Form Cell.

As far as possible, you would want to avoid checking specific values in an if state­

ment—​then this becomes a long, uncontrollable chain, as shown above.

One clever way is to divide the score by one of the eight “winning” products

(shown in color in the square above). If the remainder is 0, then the score is a winner.

Notice that this method achieves a huge simplification—​you no longer have to check

each triplet of cells. You can multiply all of them, and check for the remainder after

dividing by each winning product. If the remainder is 0, then surely it has one of the

winning combinations.